﻿using Microsoft.EntityFrameworkCore;
using Poem.Core.Entities;
using Poem.EF.EntityFramework;
using Volo.Abp.Data;
using Volo.Abp.EntityFrameworkCore;
using Volo.Abp.EntityFrameworkCore.Modeling;

namespace Poem.EF
{
    [ConnectionStringName("Poem")]
    public class PoemDbContext : AbpDbContext<PoemDbContext>, IPoemDbContext
    {
        public PoemDbContext(DbContextOptions<PoemDbContext> options) : base(options)
        {
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
            // 映射 poet
            modelBuilder.Entity<Poet>(b =>
            {
                b.ToTable("Poet");

                // 映射实体与数据库字段
                b.Property(p => p.Id).HasColumnName("PoetId");
                b.ConfigureByConvention();
            });

            // 映射 poem
            modelBuilder.Entity<Core.Entities.Poem>(b =>
            {
                b.ToTable("Poem");

                // 映射实体与数据库字段
                b.Property(p => p.Id).HasColumnName("PoemId");
                // poem与poet一对多
                b.HasOne(s => s.Author)
                    .WithMany(s => s.Poems)
                    .HasForeignKey(s => s.PoetID);
                b.ConfigureByConvention();
            });

            // 映射 category
            modelBuilder.Entity<Category>(b =>
            {
                b.ToTable("Category");

                // 映射实体与数据库字段
                b.Property(p => p.Id).HasColumnName("CategoryId");
                b.ConfigureByConvention();
            });

            // 映射 categoryPoem
            modelBuilder.Entity<CategoryPoem>(b =>
            {
                b.ToTable("CategoryPoem");

                // 映射实体与数据库字段
                b.Property(p => p.Id).HasColumnName("CategoryPoemId");
                // 多对多
                b.HasKey(t => new { t.CategoryId, t.PoemId });
                b.HasOne(pt => pt.Poem).WithMany(p => p.PoemCategories).HasForeignKey(pt => pt.PoemId);
                b.HasOne(pt => pt.Category).WithMany(t => t.CategoryPoems).HasForeignKey(t => t.CategoryId);
                b.ConfigureByConvention();
            });
            
        }

        public virtual DbSet<Poet> Poets { get; set; }
        public virtual DbSet<Core.Entities.Poem> Poems { get; set; }
        public virtual DbSet<Category> Categories { get; set; }
        public virtual DbSet<CategoryPoem> CategoryPoems { get; set; }
    }
}
